import { ref } from 'vue'
import { showToast, noneModal } from '@/utils/toast.js'
import { getTimeAfterMinutes, formatData } from '@/utils/index.js'
import { GlobalStore } from '@/stores/global.js'

export default function(devPhotonAddApi) {
	const SERVICE_ID = '0000AE3A-0000-1000-8000-00805F9B34FB'
	// const WRITE_CHARACTERISTIC_ID = '0000AE3B-0000-1000-8000-00805F9B34FB'
	// const INDICATE_CHARACTERISTIC_ID = '0000AE3C-0000-1000-8000-00805F9B34FB'

	const deviceId = ref('') // 目标蓝牙设备ID
	const deviceIdList = ref([]) // 目标蓝牙设备ID列表
	const serviceId = ref('') // 蓝牙服务UUID
	const writeCharacteristicId = ref('') // 可写特征UUID
	const indicateCharacteristicId = ref('') // 可指示特征UUID
	const bluetoothAdapterOpened = ref(false) // 蓝牙适配器打开状态
	const isConnected = ref(false) // 蓝牙连接状态
	const bluetoothDevices = ref([]) // 搜索到的蓝牙设备列表
	let devPhotonList = [] // 状态时间列表
	let deviceName = '' // 当前设备名称
	let searchCount = 0 // 搜索设备的次数计数
	
	function checkStatus(prefix, msg) {
		if (msg.includes('not init')) return noneModal(prefix + '：未初始化蓝牙适配器')
		if (msg.includes('not available')) return noneModal(prefix + '：当前蓝牙适配器不可用')
		if (msg.includes('no device')) return noneModal(prefix + '：没有找到指定设备')
		if (msg.includes('connection fail')) return noneModal(prefix + '：连接失败')
		if (msg.includes('no service')) return noneModal(prefix + '：没有找到指定服务')
		if (msg.includes('no characteristic')) return noneModal(prefix + '：没有找到指定特征值')
		if (msg.includes('no connection')) return noneModal(prefix + '：当前连接已断开')
		if (msg.includes('property not support')) return noneModal(prefix + '：当前特征值不支持此操作')
		if (msg.includes('system error')) return noneModal(prefix + '：其余所有系统上报的异常')
		if (msg.includes('system not support')) return noneModal(prefix + '：系统版本低于 4.3 不支持 BLE')
		if (msg.includes('already connect')) return noneModal(prefix + '：已连接')
		if (msg.includes('operate time out')) return noneModal(prefix + '：连接超时')
		if (msg.includes('invalid_data')) return noneModal(prefix + '：连接 deviceId 为空或者是格式不正确')
		noneModal(prefix + ': ' + msg)
	}

	// 初始化蓝牙适配器
	function initBluetooth() {
		searchCount = 0
		if (bluetoothAdapterOpened.value) {
			bluetoothAdapterOpened.value = false
			uni.closeBluetoothAdapter({
				success() {
					setTimeout(() => {
						openBluetoothAdapter()
					}, 500)
				},
				fail(err) {
					console.log('关闭蓝牙适配器失败', err.errMsg)
					// checkStatus('关闭蓝牙适配器失败', err.errMsg)
					checkStatus('关闭蓝牙适配器失败' + ': ' + err.errMsg)
				}
			})
		} else {
			openBluetoothAdapter()
		}
	}

	// 打开蓝牙适配器
	function openBluetoothAdapter() {
		uni.showLoading({
			title: '打开蓝牙适配器中...',
			mask: true,
		})
		uni.openBluetoothAdapter({
			success(res) {
				uni.hideLoading()
				bluetoothAdapterOpened.value = true
				setTimeout(() => {
					searchDevices()
				}, 500)
			},
			fail(err) {
				uni.hideLoading()
				bluetoothAdapterOpened.value = false
				console.log('打开蓝牙适配器失败', err)
				const { errMsg } = err
				if (errMsg.includes('fail open fail')) return noneModal('系统蓝牙未打开')
				if (errMsg.includes('fail auth deny')) return noneModal('请点击右上角 更多按钮(...)，设置打开蓝牙权限')
				if (errMsg.includes('system permission denied')) return noneModal('请在手机设置中开启蓝牙或打开软件蓝牙权限')
				checkStatus('打开蓝牙适配器失败: ', errMsg)
			}
		})
	}

	// 搜索蓝牙设备
	function searchDevices() {
		uni.showLoading({
			title: '搜索蓝牙设备...',
			mask: true,
		})
		uni.startBluetoothDevicesDiscovery({
			services: [],
			allowDuplicatesKey: false,
			success(res) {
				uni.hideLoading()
				setTimeout(() => {
					getBluetoothDevices()
				}, 500)
			},
			fail(err) {
				uni.hideLoading()
				console.log('搜索蓝牙设备失败', err)
				checkStatus('搜索蓝牙设备失败', err.errMsg)
			}
		})
	}

	// 获取蓝牙设备列表
	function getBluetoothDevices() {
		if (searchCount === 0) {
			uni.showLoading({
				title: '获取蓝牙设备列表...',
				mask: true,
			})
		}
		uni.getBluetoothDevices({
			success(res) {
				console.log('获取到的蓝牙设备列表', res.devices)
				bluetoothDevices.value = res.devices
				// 假设目标设备名称为特定名称，这里找到目标设备并记录其deviceId
				const targetDeviceList = bluetoothDevices.value.filter(device => device.name.includes('T670'))
				if (searchCount < 5) {
					searchCount++
					setTimeout(() => {
						getBluetoothDevices()
					}, 500)
				} else if (targetDeviceList && targetDeviceList.length > 0) {
					deviceIdList.value = Object.values(targetDeviceList.reduce((acc, current) => {
						acc[current.deviceId] = current
						return acc
					}, {}))
					uni.hideLoading()
					// console.log('deviceIdList', deviceIdList.value)
				} else {
					// 如果未找到目标设备，增加搜索次数计数
					searchCount++
					if (searchCount < 20) {
						// 搜索次数小于 20 次，再次获取设备列表
						console.log('未找到目标设备，再次搜索...')
						setTimeout(() => {
							getBluetoothDevices()
						}, 1000)
					} else {
						uni.hideLoading()
						showToast('已达到最大搜索次数，仍未找到目标设备')
					}
				}
			},
			fail(err) {
				uni.hideLoading()
				console.log('获取蓝牙设备列表失败', err)
				checkStatus('获取蓝牙设备列表失败', err.errMsg)
			}
		})
	}

	// 关闭蓝牙搜索
	function stopSearchDevices() {
		uni.stopBluetoothDevicesDiscovery({
			success(r) {
				console.log("停止搜索蓝牙设备", r)
			}
		})
	}

	// 连接蓝牙设备
	function connectDevice(currentDevName) {
		deviceName = currentDevName
		uni.showLoading({
			title: '连接蓝牙中...',
			mask: true,
		})
		uni.createBLEConnection({
			deviceId: deviceId.value,
			success(res) {
				uni.hideLoading()
				setTimeout(() => {
					uni.showLoading({
						title: '设备授权中...',
						mask: true
					})
					isConnected.value = true
					stopSearchDevices()
					// 获取设备服务
					getDeviceServices()
				}, 500)
			},
			fail(err) {
				console.log('连接蓝牙设备失败', err)
				uni.hideLoading()
				checkStatus('连接蓝牙设备失败', err.errMsg)
			}
		})
	}

	// 获取设备服务
	function getDeviceServices() {
		uni.getBLEDeviceServices({
			deviceId: deviceId.value,
			success(res) {
				console.log('获取到的服务列表', res.services)
				serviceId.value = res.services.find(service => service.uuid.toLocaleUpperCase() === SERVICE_ID).uuid
				console.log('serviceId', serviceId.value)
				if (serviceId.value) {
					// 获取设备特征
					setTimeout(() => {
						getDeviceCharacteristics()
					}, 1500)
				} else {
					uni.hideLoading()
					showToast('未找到相应的服务uuid')
				}
			},
			fail(err) {
				uni.hideLoading()
				console.log('获取服务列表失败', err)
				checkStatus('获取服务列表失败', err.errMsg)
			}
		})
	}

	// 获取设备特征
	function getDeviceCharacteristics() {
		uni.getBLEDeviceCharacteristics({
			deviceId: deviceId.value,
			serviceId: serviceId.value,
			success(res) {
				console.log('获取到的特征列表', res.characteristics)
				res.characteristics.forEach(item => {
					if (item.properties.notify === true) {
						indicateCharacteristicId.value = item.uuid
					}
					if (item.properties.write === true) {
						writeCharacteristicId.value = item.uuid
					}
				})
				if (!writeCharacteristicId.value || !indicateCharacteristicId.value) {
					uni.hideLoading()
					showToast('未找到相应特征列表的uuid')
				} else {
					startNotice()
					setTimeout(() => {
						syncTime()
					}, 500)
				}
			},
			fail(err) {
				uni.hideLoading()
				console.log('获取特征列表失败', err)
				checkStatus('获取特征列表失败', err.errMsg)
			}
		})
	}

	// 同步时间
	function syncTime() {
		const now = new Date()
		const year = now.getFullYear() % 100
		const month = now.getMonth() + 1
		const day = now.getDate()
		const hour = now.getHours()
		const minute = now.getMinutes()
		const second = now.getSeconds()
		const temp = [0x01, 0x06, year, month, day, hour, minute, second]
		// 24 11 07 22 00 02
		// const temp = [0x01, 0x06, 24, 10, 30, 22, 0, 2]
		const crc = calcCrc8(temp, 8, 0xAB)
		const buffer = new Uint8Array([...temp, crc])
		// const buffer = new Uint8Array([...temp, 0xF9])
		// console.log('buffer', buffer.buffer)
		uni.writeBLECharacteristicValue({
			deviceId: deviceId.value,
			serviceId: serviceId.value,
			characteristicId: writeCharacteristicId.value,
			value: buffer.buffer,
			success(res) {
				console.log('同步时间指令发送成功，等待应答')
			},
			fail(err) {
				uni.hideLoading()
				console.log('同步时间指令发送失败', err)
				checkStatus('同步时间指令发送失败', err.errMsg)
			}
		})
	}

	// 同步时间指令应答处理
	function onSyncTimeResponse(res) {
		const value = new Uint8Array(res.value)
		if (value[0] === 0x01 && value[1] === 0x01) {
			const err = value[2]
			if (err === 0x00) {
				console.log('同步时间成功')
				deviceAuth()
				// 同步时间成功后可以进行设备授权等其他操作
			} else {
				uni.hideLoading()
				showToast('同步时间失败')
			}
		}
	}

	// 设备授权
	function deviceAuth() {
		// 终止时间
		const times = GlobalStore().times
		const { year, month, day, hour, minute, second } = getTimeAfterMinutes(times)
		const temp = [0x00, 0x06, year % 100, month, day, hour, minute, second]
		// console.log('deviceAuth', year % 100, month, day, hour, minute, second)
		// const temp = [0x00, 0x06, 24, 11, 13, 14, 50, 0]
		const crc = calcCrc8(temp, 8, 0xAB)
		const buffer = new Uint8Array([...temp, crc])
		uni.writeBLECharacteristicValue({
			deviceId: deviceId.value,
			serviceId: serviceId.value,
			characteristicId: writeCharacteristicId.value,
			value: buffer.buffer,
			success() {
				console.log('设备授权指令发送成功，等待应答')
			},
			fail(err) {
				uni.hideLoading()
				console.log('设备授权指令发送失败', err)
				checkStatus('设备授权指令发送失败', err.errMsg)
			}
		})
	}

	// 设备授权指令应答处理
	function onDeviceAuthResponse(res) {
		const value = new Uint8Array(res.value)
		if (value[0] === 0x00 && value[1] === 0x01) {
			const err = value[2]
			if (err === 0x00) {
				console.log('设备授权成功')
				setTimeout(() => {
					console.log('请求数据')
					requestData()
				}, 500)
			} else {
				uni.hideLoading()
				showToast('设备授权失败')
			}
		}
	}

	// 请求数据
	function requestData(num = 0) {
		const temp = [0x02, 0x01, num]
		const crc = calcCrc8(temp, 3, 0xAB)
		const buffer = new Uint8Array([...temp, crc])
		uni.writeBLECharacteristicValue({
			deviceId: deviceId.value,
			serviceId: serviceId.value,
			characteristicId: writeCharacteristicId.value,
			value: buffer.buffer,
			success(res) {
				console.log('数据请求指令发送成功，等待应答')
			},
			fail(err) {
				uni.hideLoading()
				console.log('数据请求指令发送失败', err)
				checkStatus('数据请求指令发送失败', err.errMsg)
			}
		})
	}

	// 数据请求指令应答处理
	function onDataRequestResponse(res) {
		const value = new Uint8Array(res.value)
		if (value[0] === 0x02 && value[1] === 0x0A) {
			const num = value[2]
			const state = value[3]
			const time = new Date(
				2000 + value[4], value[5] - 1, value[6], value[7], value[8], value[9]
			)
			const total = value[10]
			const err = value[11]
			if (err === 0x00) {
				console.log('数据请求成功，包序号:', num, '灯状态:', state, '时间:', time, '总包数:', total)
				devPhotonList.push({
					statusFlag: state === 1,
					eventAt: formatData(time)
				})
				// 如果包序号小于总包数 - 1，可以继续取下一个包
				if (num < total - 1) {
					requestData(num + 1)
				} else {
					const { socialId, openId, nickName } = GlobalStore()
					devPhotonAddApi({
						socialId,
						openId,
						name: deviceName,
						nickName,
						items: devPhotonList
					}).finally(() => {
						uni.hideLoading()
						setTimeout(() => {
							showToast('授权成功')
						}, 500)
					})
					// uni.hideLoading()
				}
			} else {
				deviceName = ''
				devPhotonList = []
				uni.hideLoading()
				console.log('数据请求失败')
				setTimeout(() => {
					showToast('授权成功')
				}, 500)
			}
		}
	}

	function startNotice() {
		uni.notifyBLECharacteristicValueChange({
			characteristicId: indicateCharacteristicId.value,
			deviceId: deviceId.value,
			serviceId: serviceId.value,
			state: true,
			success(res) {
				// 监听低功耗蓝牙设备的特征值变化
				uni.onBLECharacteristicValueChange(res => {
					console.log('听低功耗蓝牙设备的特征值变化 success', res)
					const value = new Uint8Array(res.value)
					// 指令类型
					const type = value[0]
					switch (type) {
						case 0x00:
							// 授权
							onDeviceAuthResponse(res)
							break
						case 0x01:
							// 同步时间
							onSyncTimeResponse(res)
							break
						case 0x02:
							// 发送请求
							onDataRequestResponse(res)
							break
						default:
							break
					}
				})
			},
			fail(res) {
				uni.hideLoading()
				console.log('res', res)
			}
		})
	}

	// 断开蓝牙连接
	function disconnectDevice() {
		uni.closeBLEConnection({
			deviceId: deviceId.value,
			success: res => {
				console.log('断开蓝牙连接成功', res)
				isConnected.value = false
				deviceName = ''
				devPhotonList = []
				// 可以在这里进一步清理相关数据或状态
			},
			fail: err => {
				console.log('断开蓝牙连接失败', err)
				if (err && err.errMsg === 'closeBLEConnection:fail:no connection') {
					isConnected.value = false
				} else {
					checkStatus('断开蓝牙连接失败', err.errMsg)
				}
			}
		})
	}

	// CRC8校验方法
	function calcCrc8(data, len, chr) {
		let crc = chr
		for (let i = 0; i < len; i++) {
			crc ^= data[i] & 0xFF
			for (let j = 8; j > 0; j--) {
				if (crc & 0x80) {
					crc <<= 1
					crc ^= 0x2F
				} else {
					crc <<= 1
				}
			}
		}
		return crc & 0xFF
	}

	return {
		deviceId,
		deviceIdList,
		isConnected,
		initBluetooth,
		connectDevice,
		disconnectDevice,
		searchDevices,
		searchCount
	}
}